<!DOCTYPE html>
<html lang="en">
<title>添加新团课</title>
<#import "/layout/layout.html" as body/>
<@body.page>

<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-lg-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title overflow">
                    <h5 class="pull-left">添加新团课</h5>
                </div>
                <div class="ibox-content">
                    <form method="post" class="form-horizontal" enctype="multipart/form-data" action="#" name="addForm" id="addForm">
                        <div class="form-group"><h3 class="col-sm-12 margin-top">预定信息</h3></div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">团课名称</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" maxlength="50" name="title" id="title" placeholder="请输入不超过50字的团课名称">
                                <span class="help-block m-b-none text-right">
                                        <i class="pull-right">0/50</i>
                                    </span>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">上课教练</label>

                            <div class="col-sm-10">
                                <select class="form-control m-b chosen-select" name="courseCoach.coachId" id="coachId">
                                    <#if coachList??>
                                        <#list coachList as coach>
                                            <option value="${coach.id}">${coach.nickName!}</option>
                                        </#list>
                                    </#if>
                                </select>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">课程费用</label>

                            <div class="col-sm-10">
                                <div class="input-group m-b"><span class="input-group-addon">¥</span>
                                    <input name="servicePrice.primePrice" id="primePrice" type="number" class="form-control" placeholder="请输入课程费用">
                                </div>
                                <!--<input type="number" class="form-control" name="price" id="price" placeholder="">-->
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">会员费用</label>
                            <div class="col-sm-10">
                                <div class="input-group m-b"><span class="input-group-addon">¥</span>
                                    <input name="servicePrice.price" id="price" type="number" class="form-control" placeholder="非必填，如果设置该价格，则针对会员收取该价格，如未填写，则按照课程费用X固定折扣收取会员费用。">
                                </div>
                                <div class="checkbox checkbox-primary">
                                    <input id="isVipUsed" type="checkbox" name="isVipUsed" value="0"/>
                                    <label for="isVipUsed">是否设为会员独享课</label>
                                </div>
                            </div>
                        </div>


                        <div class="form-group"><label class="col-sm-2 control-label">最大报名人数</label>

                            <div class="col-sm-10">
                                <input type="number" class="form-control" name="maxCount" id="maxCount" placeholder="请输入最大报名人数">
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">上课门店</label>

                            <div class="col-sm-10">
                                <select id="storeId" name="storeId" data-placeholder="请选择上课门店" class="form-control m-b chosen-select"
                                        style="width:100%;" tabindex="4">
                                    <#if storeList??>
                                        <#list storeList as store>
                                            <option value="${store.id}">${store.storeName!}</option>
                                        </#list>
                                    </#if>
                                </select>
                            </div>
                        </div>

                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">上课操房</label>
                            <div class="col-sm-10">
                                <select id="workoutRoomNum" name="workoutRoomNum" class="form-control m-b chosen-select" style="width:100%;" tabindex="4">

                                </select>
                            </div>
                        </div>


                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">上课日期</label>

                            <div class="col-sm-10">
                                <div class="input-group date">
                                    <span class="input-group-addon"><i class="fa fa-calendar"></i></span>
                                    <input type="text" class="form-control" name="startDate" id="startDate" placeholder="请选择上课日期" readonly>
                                </div>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">开始结束时间</label>
                            <div class="col-sm-10">
                                <div class="col-sm-6 padding-left-0">
                                    <div class="input-group clockpicker" data-autoclose="true">
                                        <input type="text" class="form-control" value="" name="startTime" id="startTime" placeholder="开始时间" readonly>
                                        <span class="input-group-addon"><span class="fa fa-clock-o"></span></span>
                                    </div>
                                    <h5>开始时间</h5>
                                </div>
                                <div class="col-sm-6 padding-right-0">
                                    <div class="input-group clockpicker" data-autoclose="true">
                                        <input type="text" class="form-control" value="" name="endTime" id="endTime" placeholder="结束时间" readonly>
                                        <span class="input-group-addon"><span class="fa fa-clock-o"></span></span>
                                    </div>
                                    <h5>结束时间</h5>
                                </div>
                            </div>
                        </div>
                        <!--<div class="hr-line-dashed"></div>-->
                        <!--<div class="form-group"><label class="col-sm-2 control-label">团课群二维码</label>-->

                            <!--<div class="col-sm-10">-->
                                <!--<input type="hidden" id="qunQRCodePic" name="qunQRCodePic">-->
                                <!--<div id="qun_qr_code" style="min-height: 150px;" class="dropzone" action="#">-->
                                    <!--<div class="dropzone-previews"></div>-->
                                <!--</div>-->
                            <!--</div>-->
                        <!--</div>-->
                        <div class="hr-line-dashed"></div>
                        <div class="form-group">
                            <h3 class="col-sm-12 margin-top-5">课程信息
                                <small>(选择课程所属类别后，系统会自动拉取对应的标准课程信息，您可根据需要自行调整文字及图片信息)</small>
                            </h3>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">所属类别</label>
                            <div class="col-sm-10">
                                <select class="form-control m-b" name="courseStandardId" id="courseStandardId">
                                    <option value="0">无</option>
                                    <#if courseStandards??>
                                        <#list courseStandards as courseStandard>
                                            <option value="${courseStandard.id}">${courseStandard.name}</option>
                                        </#list>
                                    </#if>
                                </select>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">类别介绍文字</label>

                            <div class="col-sm-10">
                                <textarea class="form-control" rows="5" maxlength="600" id="introduce" name="introduce" placeholder="请输入类别介绍"></textarea>
                                <span class="help-block m-b-none">字数不超过600汉字；可分段描述
                                        <i class="pull-right">0/600</i>
                                    </span>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">适合人群</label>

                            <div class="col-sm-10">
                                <textarea class="form-control" rows="3" maxlength="600" id="crowd" name="crowd" placeholder="请输入适合人群"></textarea>
                                <span class="help-block m-b-none">字数不超过600汉字；可分段描述
                                        <i class="pull-right">0/600</i>
                                    </span>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">属性标签</label>
                            <input id="courseAttr" name="courseAttr" type="hidden">
                            <div class="col-sm-10">
                                <div id="magicsuggest"></div>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">视频链接</label>
                            <div class="col-sm-10"><input type="text" class="form-control" name="link" id="link" placeholder="请输入视频链接"></div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">视频封面图</label>
                            <div class="col-sm-10">
                                <div id="video_preview" style="min-height: 230px;" class="dropzone"
                                     action="#">
                                    <input type="hidden" id="url" name="url">
                                    <div class="dropzone-previews"></div>
                                </div>
                            </div>
                        </div>
                        <div class="hr-line-dashed"></div>
                        <div class="form-group"><label class="col-sm-2 control-label">类别硬照</label>

                            <div class="col-sm-10">
                                <div id="category_pic" style="min-height: 230px;" class="dropzone"
                                     action="#">
                                    <input type="hidden" id="categoryPic" name="categoryPic">
                                    <div class="dropzone-previews"></div>
                                </div>
                                <div class="m text-left">
                                    <small>大小不能超过1.5M;必须大于两张，且总数为偶数。</small>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="ibox-content overflow">
                    <div class="col-sm-12">
                        <button type="button" onclick="goBackList()" class="btn btn-default pull-left">取消添加</button>
                        <button type="button" id="saveBtn" onclick="saveCourse()" class="btn btn-primary pull-right">确认创建</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!--upload-->
<script type="text/javascript" src="${baseUrl}js/upload/promise.min.js"></script>
<script type="text/javascript" src="${baseUrl}js/upload/aliyun-oss-sdk.min.js"></script>
<script type="text/javascript" src="${baseUrl}js/upload/webToOss.js"></script>

<script src="${baseUrl}js/plugins/dropzone/dropzone.js"></script>
<link href="${baseUrl}css/plugins/clockpicker/clockpicker.css" rel="stylesheet">
<script src="${baseUrl}js/plugins/clockpicker/clockpicker.js"></script>
<link href="${baseUrl}css/plugins/magicsuggest/magicsuggest-min.css" rel="stylesheet">

<script>
    var ms = null;//下拉插件
    var dictArr = new Array();
    var dataDictList = ${dataDictList!};
    $('.clockpicker').clockpicker();
    var qrcodePicList = new Array();//群QRCODE
    var videoLinkPicList = new Array();//视频封面
    var categoryPicList = new Array();//类别硬照
    var myDropzone1;
    var myDropzone2;
    var myDropzone3;

    //返回列表
    function goBackList() {
        window.location = "to_course_team_query";
    }
    //保存方法
    function saveCourse() {

        var isCheck = true;
        //校验表单
        if ($("#title").val().length <= 0) {
            swal("错误!", "请先填写团课名称!", "error");
            isCheck = false;
            return false;
        }
        if ($("#primePrice").val().length <= 0) {
            swal("错误!", "请先输入课程费用!", "error");
            isCheck = false;
            return false;
        }

        if ($("#maxCount").val().length <= 0) {
            swal("错误!", "请输入课程最大人数!", "error");
            isCheck = false;
            return false;
        }

        if ($("#maxCount").val() < 0) {
            swal("错误!", "课程最大人数应大于0!", "error");
            isCheck = false;
            return false;
        }

        if ($("#primePrice").val() < 0) {
            swal("错误!", "课程金额必须大于等于0!", "error");
            isCheck = false;
            return false;
        }

        if ($("#storeId").val() == null) {
            swal("错误!", "请先选择上课门店!", "error");
            isCheck = false;
            return false;
        }

        debugger;
        if ($('#isVipUsed').prop('checked')) {
            $('#isVipUsed').val(1);
        } else {
            $('#isVipUsed').attr("value", 0);
        }


        var date = $("#startDate").val();
        if (date.length == 0) {
            swal("错误!", "日期不能为空!", "error");
            isCheck = false;
            return false;
        }
        var startTime = $("#startTime").val();
        if (startTime == null || startTime == "undefined" || startTime == undefined || startTime == "") {
            swal("错误!", "开始时间不能为空!", "error");
            isCheck = false;
            return false;
        }
        var endTime = $("#endTime").val();
        if (endTime == null || endTime == "undefined" || endTime == undefined || endTime == "") {
            swal("错误!", "结束时间不能为空!", "error");
            isCheck = false;
            return false;
        }


        if (startTime >= endTime) {
            swal("错误!", "课程结束时间必须晚于课程开始时间!", "error");
            isCheck = false;
            return false;
        }

//        $("#qunQRCodePic").val(qrcodePicList.join(","));
//        if ($("#qunQRCodePic").val().length <= 0) {
//            swal("错误!", "请先上传檬营群二维码!", "error");
//            isCheck = false;
//            return false;
//        } else {
//            if ($("#qunQRCodePic").val().split(",").length != 1) {
//                swal("错误!", "请先确定上传1张数量的檬营群二维码!", "error");
//                isCheck = false;
//                return false;
//            }
//        }
        if ($("#introduce").val().length <= 0) {
            swal("错误!", "请先输入类别介绍文字!", "error");
            isCheck = false;
            return false;
        }
        if ($("#crowd").val().length <= 0) {
            swal("错误!", "请先输入适合人群!", "error");
            isCheck = false;
            return false;
        }
        $("#courseAttr").val(dictArr.toString());
        if ($("#courseAttr").val() == "") {
            swal("错误!", "请先选择属性标签!", "error");
            isCheck = false;
            return false;
        }


        $("#url").val(videoLinkPicList.join(","));
        if (videoLinkPicList.length > 0 && videoLinkPicList.length != 1) {
            swal("错误!", "请先确定上传1张数量的视频封面图!", "error");
            isCheck = false;
            return false;
        }

        $("#categoryPic").val(categoryPicList.join(","));
        if ($("#categoryPic").val().length <= 0) {
            swal("错误!", "请先上传类别硬照!", "error");
            isCheck = false;
            return false;
//        } else {
//            if ($("#categoryPic").val().split(",").length % 2 != 0) {
//                swal("错误!", "请先上传偶数量的类别硬照!", "error");
//                isCheck = false;
//                return false;
//            }
        }

        if (!isCheck) {
            return false;
        }
        var param = $("#addForm").serialize();

        $("#saveBtn").attr('disabled', "true");
        $.ajax({
            type: "post",
            url: "to_course_team_save",
            data: param,
            success: function (data) {
                if (data == "success") {
                    swal("保存成功!", "页面即将重新加载,请稍后...", "success");
                    window.setTimeout(function () {
                        window.location = "to_course_team_query"
                    }, 1000);
                } else {
                    swal("保存失败!", data, "error");
                }
            }
        });
    }
    $(document).ready(function () {

        ms = $('#magicsuggest').magicSuggest({
            data: dataDictList,
            placeholder: '请输入搜索或选择',
            required: true,
            expandOnFocus: true,
            strictSuggest: true,
            displayField: 'dictName',
            valueField: 'dictName'
        });

        $(ms).on('selectionchange', function () {
            console.log('DATA---->>' + JSON.stringify(this.getValue()));
            dictArr = this.getValue();
        });

        //截止报名时间
        $('.input-group.date').datepicker({
            todayBtn: "linked",
            keyboardNavigation: false,
            format: 'yyyy-mm-dd',
            forceParse: false,
            autoclose: true
        });

        Dropzone.autoDiscover = false;
        //视频封面图
        myDropzone2 = new Dropzone("#video_preview", {
            url: "upload_pic",
            uploadMultiple: false,
            addRemoveLinks: true,
            dictDefaultMessage: "将文件拖到此处上传",
            dictFileTooBig: "文件过大",
            dictCancelUpload: "取消上传",
            dictRemoveFile: "移除文件",
            dictMaxFilesExceeded: "超过上传文件数量限制",
            maxFiles: 1,
            maxFilesize: 10.5,
            acceptedFiles: ".jpg,.jpeg,.png",
            method: 'post',
            filesizeBase: 1024,

            init: function () {
//                     var url = $("#url").val();
//                     if (!url || url.length <= 0) {
//                        url = "";
                //                    } else {
                //                        var larr = url.split(",");
                //                        if (larr.length >0){
                //                            for(var i=0;i<larr.length;i++){
                //                                videoLinkPicList.push(larr[i]);
                //                            }
                //                        }
                //                   }
                //                   this.emit("initimage", url);
                this.on("success", function (file, response, e) {
                    if (response.error) {
                        $(file.previewTemplate).children('.dz-error-mark').css('opacity', '1')
                    } else {
                        videoLinkPicList.push(response.url);
                    }
                });
                this.on("sending", function (file, xhr, formData) {
                    formData.append("filesize", file.size);
                });
                this.on("removedfile", function (file) {
                    var responseJson = null;
                    if (file && file.xhr && file.xhr.responseText) {
                        responseJson = $.parseJSON(file.xhr.responseText);
                    }
                    if (responseJson) {
                        $.each(videoLinkPicList, function (i, data) {
                            if (videoLinkPicList[i].indexOf(responseJson.url) > -1) {
                                videoLinkPicList.splice(i, 1);
                            }
                        });
                        /**
                         $.post("delete_pic", {fileName: responseJson.url}, function (result) {
                                 if (result) {
                                     console.log(responseJson.url + '删除成功');
                                 }
                             });*/
                    }
                    if (file.name.length > 0) {
                        $.each(videoLinkPicList, function (i, data) {
                            if (videoLinkPicList[i].indexOf(file.name) > -1) {
                                /**
                                 $.post("delete_pic", {fileName: videoLinkPicList[i]}, function (result) {
                                         if (result) {
                                             console.log(videoLinkPicList[i] + '删除成功');
                                         }
                                     });*/
                                videoLinkPicList.splice(i, 1);
                            }
                        });
                    }
                    console.log("文件 " + file.name + " 被移除");
                });
            }
        });


        //类别硬照
        myDropzone3 = new Dropzone("#category_pic", {
            url: "upload_pic",
            uploadMultiple: false,
            addRemoveLinks: true,
            dictDefaultMessage: "将文件拖到此处上传",
            dictFileTooBig: "文件过大",
            dictCancelUpload: "取消上传",
            dictRemoveFile: "移除文件",
            maxFilesize: 10.5,
            acceptedFiles: ".jpg,.jpeg,.png",
            method: 'post',
            filesizeBase: 1024,

            init: function () {
                //                    var url = $("#categoryPic").val();
                //                    if (!url || url.length <= 0) {
                //                       url = "";
                //                 }else{
                //                    var larr = url.split(",");
                //                    if (larr.length >0){
                //                        for(var i=0;i<larr.length;i++){
                //                            categoryPicList.push(larr[i]);
                //                        }
                //                    }
                //                }
                //                this.emit("initimage", url);
                this.on("success", function (file, response, e) {
                    if (response.error) {
                        $(file.previewTemplate).children('.dz-error-mark').css('opacity', '1')
                    } else {
                        categoryPicList.push(response.url);
                    }
                });
                this.on("sending", function (file, xhr, formData) {
                    formData.append("filesize", file.size);
                });
                this.on("removedfile", function (file) {
                    var responseJson = null;
                    if (file && file.xhr && file.xhr.responseText) {
                        responseJson = $.parseJSON(file.xhr.responseText);
                    }
                    if (responseJson) {
                        $.each(categoryPicList, function (i, data) {
                            if (categoryPicList[i].indexOf(responseJson.url) > -1) {
                                categoryPicList.splice(i, 1);
                            }
                        });
                        /**
                         $.post("delete_pic", {fileName: responseJson.url}, function (result) {
                                 if (result) {
                                     console.log(responseJson.url + '删除成功');
                                 }
                             });*/
                    }
                    if (file.name.length > 0) {
                        $.each(categoryPicList, function (i, data) {
                            if (categoryPicList[i].indexOf(file.name) > -1) {
                                /**
                                 $.post("delete_pic", {fileName: categoryPicList[i]}, function (result) {
                                         if (result) {
                                             console.log(categoryPicList[i] + '删除成功');
                                         }
                                     });*/
                                categoryPicList.splice(i, 1);
                            }
                        });
                    }
                    console.log("文件 " + file.name + " 被移除");
                });
            }
        });

        $('.form_datetime').datetimepicker({
            language: 'zh-CN',
            weekStart: 1,
            todayBtn: 1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            forceParse: 0,
            showMeridian: 0
        });

        //loadStandard($("#courseStandardId").children('option:selected').val(), false);

        bindEventer('title', 50);
        bindEventer('coachComment', 50);
        bindEventer('introduce', 600);
        bindEventer('crowd', 600);

        $("#title, #coachComment, #introduce, #crowd").trigger("keyup");

        $("#storeId").trigger("change");
    });

    //动态改变基础课程值
    $("#courseStandardId").change(function () {
        var id = $(this).children('option:selected').val();
        debugger;
        if (id == '0') {
            //为空清空标准课程
            $('#url').val('');
            $('#introduce').val('');
            $('#crowd').val('');
            $('#link').val('');
            ms.clear();
            ms.collapse();
            $('#video_preview .dz-image-preview').remove();
            videoLinkPicList = new Array;
        } else {
            loadStandard(id, false);
        }

    })
    /**
     * 读取标准课程数据
     * @param id
     * @param isFirst 是否首次调用 ture 是 /false 不是
     */
    function loadStandard(id, isFirst) {
        $.ajax({
            type: "post",
            url: "course_standard",
            data: {"id": id},
            success: function (data) {
                courseStandard = $.parseJSON(data);
                if (courseStandard) {
                    if (!isFirst) {//非第一次进入调用才更新标准课程关联字段

                        $("#introduce").val(courseStandard.introduce).trigger("keyup");
                        $("#crowd").val(courseStandard.crowd).trigger("keyup");
                        $("#link").val(courseStandard.link);
                        $("#video_preview .dz-image-preview, #category_pic .dz-image-preview").remove();
                        videoLinkPicList = new Array;
                        if (courseStandard.url && courseStandard.url.length > 0) {
                            videoLinkPicList.push(courseStandard.url);
                            var mockFile = {name: courseStandard.url, accepted: true};
                            myDropzone2.emit("addedfile", mockFile);
                            myDropzone2.emit("thumbnail", mockFile, courseStandard.url);
                            myDropzone2.emit("complete", mockFile);
                        }
                        categoryPicList = new Array();
                        if (courseStandard.categoryPic && courseStandard.categoryPic.length > 0) {
                            var urlArr = courseStandard.categoryPic.split(",");
                            for (var i = 0; i < urlArr.length; i++) {
                                categoryPicList.push(urlArr[i]);
                                var mockFile = {name: urlArr[i], accepted: true};
                                myDropzone3.emit("addedfile", mockFile);
                                myDropzone3.emit("thumbnail", mockFile, urlArr[i]);
                                myDropzone3.emit("complete", mockFile);
                            }
                        }
                        if (courseStandard.courseAttr && courseStandard.courseAttr.length > 0) {
                            var cd = courseStandard.courseAttr.split("#");
                            ms.clear();
                            ms.setValue(cd);
                            ms.collapse();
                        } else {
                            ms.clear();
                            ms.collapse();
                        }
                    }
                }
            }
        });
    }

    /**
     * 拉取对应门店 ID 的门禁设备
     *
     * @param storeId 门店 ID
     */
    $("#storeId").change(function () {
        var param = {
            storeId: this.value
        };
        $("#workoutRoomNum").html("");
        $.post("${baseUrl}system/course/storeAccessList", param, function (result) {
            result = JSON.parse(result);
            var option = "<option value='num'>name</option>";
            var html = "";
            $.each(result, function (i, data) {
                html +=(option.replace('num',data.workoutRoomNum).replace('name', data.workoutRoomName))
            });
            $("#workoutRoomNum").html(html);
        });
    });

</script>

</@body.page>
</html>